﻿using System;
using System.Collections.Generic;
using DomainModel;
using NHibernate;
using Repository.Abstract;

namespace Repository.NHibernate
{
    public abstract class Repository<T> : IRepository<T> where T: BaseEntity
    {
        protected ISession Session = null;

        protected Repository()
        {
            Session = NHibernateHelper.OpenSession();
        }

        public virtual void SaveOrUpdate(T entity)
        {
            ITransaction tx = Session.BeginTransaction();
            try
            {
                Session.SaveOrUpdate(entity);

                tx.Commit();
            }
            catch (Exception)
            {
                tx.Rollback();
            }
        }

        public virtual T GetById(long id)
        {
            return Session.Get<T>(id);
        }

        public virtual IEnumerable<T> GetAll()
        {
            return Session.QueryOver<T>().List<T>();
        }

        public virtual void Delete(T entity)
        {
            ITransaction tx = Session.BeginTransaction();
            try
            {
                Session.Delete(entity);

                tx.Commit();
            }
            catch (Exception)
            {
                tx.Rollback();
            }
        }
    }
}
